package com.fzt.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzt.reggie.dto.DishDto;
import com.fzt.reggie.entity.Dish;
import com.fzt.reggie.entity.DishFlavor;
import com.fzt.reggie.mapper.DishMapper;
import com.fzt.reggie.service.DishFavorService;
import com.fzt.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFavorService dishFavorService;
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品信息
        this.save(dishDto);
        Long dishId = dishDto.getId();

        //保存口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setIsDeleted(1);
            flavor.setDishId(dishId);
            dishFavorService.save(flavor);
        }
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {

        this.updateById(dishDto);

        //更新dishflavor表
        //删除原有数据
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFavorService.remove(queryWrapper);
        List<DishFlavor> flavors = dishDto.getFlavors();
        //插入更新数据
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
            dishFavorService.save(flavor);
        }
    }
}
